package com.example.servicegateway.route.rule.listener;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.example.servicegateway.route.rule.AutoAddRouter;
import com.example.servicegateway.route.rule.validator.AddRuleValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 通过监听nacos服务上下线触发自动添加网关规则
 * @author K
 */
@Slf4j
@Component
public class AutoAddRuleListener {

    @Resource
    private NacosServiceDiscovery nacosServiceDiscovery;

    @Resource
    private AddRuleValidator addRuleValidator;

    @Resource
    private AutoAddRouter autoAddRouterConfig;

    @EventListener(classes = HeartbeatEvent.class)
    public void listenNacosEvent() {
        try {
            List<String> serviceNames = nacosServiceDiscovery.getServices();
            log.info("nacos服务名列表：" + serviceNames);

            if (addRuleValidator.isAllMatchServiceNams(serviceNames)) {
                log.info("没有新服务，不需要添加规则");
                return;
            }

            autoAddRouterConfig.addRouterRule(serviceNames);
        } catch (Exception e) {
            log.warn("", e);
        }
    }
}
